const connection = require("./../app/database");
const { to } = require("./../utils");

class UserService {
    async register(userInfo) {
        // 1.获取用户
        const { name, password } = userInfo;
        // 2.拼接statement
        const statement = "INSERT INTO `user` (name,password) VALUES (?,?)";
        // 3.执行sql语句
        const [error, resp] = await to(connection.execute(statement, [name, password]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async findUserByName(name) {
        const statement = "SELECT * FROM `user` WHERE name = ?";
        const [error, resp] = await to(connection.execute(statement, [name]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async updateAvatarUrl(avatarUrl, userId) {
        const statement = "UPDATE `user` SET avatar_url = ? WHERE id = ?";
        const [error, resp] = await to(connection.execute(statement, [avatarUrl, userId]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async updateUserNameOrPassword(name, password, id) {
        const statement =
            name !== undefined && password !== undefined
                ? `UPDATE user SET name = ? , password = ? WHERE id = ?`
                : name === undefined && password !== undefined
                ? `UPDATE user SET password = ? WHERE id = ?`
                : `UPDATE user SET name = ? WHERE id = ?`;
        const [error, resp] = await to(
            connection.execute(
                statement,
                [name, password, id].filter((item) => item !== undefined)
            )
        );
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async accountCancellationByUserId(id) {
        const statement = "DELETE FROM `user` WHERE id = ?";
        const [error, resp] = await to(connection.execute(statement, [id]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }
}

module.exports = new UserService();
